package ca.seia.comp6521.a2.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import ca.seia.comp6521.a2.itemsetstorage.ExternilizableItems;

public class DataFileWriter {
	private String appendModeFilePath;
	private boolean isFirstWrite = true;
	private BufferedWriter bufferedWriter;
	
	
	public DataFileWriter() {
	}
	
	public DataFileWriter(String appendModeFilePath) throws IOException {
		this(appendModeFilePath, createBufferedWriter(appendModeFilePath, false));
	}


	public DataFileWriter(String appendModeFilePath,
			BufferedWriter bufferedWriter) {
		this.appendModeFilePath = appendModeFilePath;
		this.bufferedWriter = bufferedWriter;
	}
	
	public void writeLine(String line) throws IOException {
		this.bufferedWriter.write(line);
		this.bufferedWriter.newLine();
		this.bufferedWriter.close();
		
	}
	
	public void writeItems(int item1, int item2, int count) throws IOException {
		setWriteMode();
		this.bufferedWriter.write(item1 + " " +item2 + " sup=" + count + "\r\n");
//		this.bufferedWriter.write(items.toExternalFormat() + " " + count);
//		this.bufferedWriter.newLine();
//		System.out.println("writting " + items.toExternalFormat());
		this.bufferedWriter.close();
	}
	
	public void writeItems(ExternilizableItems items, int count) throws IOException {
		setWriteMode();
		this.bufferedWriter.write(items.toExternalFormat() + " sup=" + count + "\r\n");
//		this.bufferedWriter.write(items.toExternalFormat() + " " + count);
//		this.bufferedWriter.newLine();
//		System.out.println("writting " + items.toExternalFormat());
		this.bufferedWriter.close();
	}
	
	
	public void writeItems(ExternilizableItems items, int count, boolean isFinalItem) throws IOException {
		setWriteMode();
		this.bufferedWriter.write(items.toExternalFormat() + " sup=" + count + "\r\n");
//		this.bufferedWriter.write(items.toExternalFormat() + " " + count);
//		this.bufferedWriter.newLine();
//		System.out.println("writting " + items.toExternalFormat());
		if(isFinalItem) {
			this.bufferedWriter.close();
		}
	}
	
	public void close() throws IOException {
		this.bufferedWriter.close();
	}
	
	public void setCreationMode() throws IOException {
		this.isFirstWrite = true;
		this.bufferedWriter = createBufferedWriter(appendModeFilePath, false);
	}
	
	public void setAppendMode() {
		this.isFirstWrite = false;
	}
	
	private void setWriteMode() throws IOException {
		if( isFirstWrite ) {
			this.isFirstWrite = false;
		} else {
			this.bufferedWriter = createBufferedWriter(appendModeFilePath, true);
		}
	}
	
	private static BufferedWriter createBufferedWriter(String filePath,boolean append) throws IOException {
		return new BufferedWriter(new FileWriter(filePath,append));
	}
}
